package com.db.priceApp.domain;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;

public class InstrumentList {

	private ConcurrentHashMap<String, Price> instrumentlist;
	private Logger logger = Logger.getLogger(InstrumentList.class.getName());

	public InstrumentList(ConcurrentHashMap<String, Price> instrumentlist) {

		this.instrumentlist = instrumentlist;
	}

	public void setDefaultInstrumentList() {		
		instrumentlist.put("GA", new Price(5, 10));
		instrumentlist.put("GB", new Price(10, 15));
		instrumentlist.put("GC", new Price(15, 20));
	}
	
	public InstrumentList() {
		instrumentlist = new ConcurrentHashMap<String, Price>();
	}

	public void addInstrument (String instrName, Price price){
		instrumentlist.put(instrName, price);
	}

	public Set<String> getInstrumentList() {
		return Collections.unmodifiableSet(instrumentlist.keySet());
	}

	public Price getInstrumentPrice(String instrName) throws IllegalArgumentException {
		Price price = null;
		try {
			price = instrumentlist.get(instrName);
		} catch (NullPointerException e) {
			logger.warning("no such instrument " + instrName);
			throw new IllegalArgumentException("no such instrument "
					+ instrName);
		}
		return price;
	}

	public void changeInstrumentPrice(String instrName, Price price)
			throws IllegalArgumentException {

		try {
			instrumentlist.replace(instrName, price);
		} catch (NullPointerException e) {
			logger.warning("illegal name of the instrument " + instrName);
			throw new IllegalArgumentException("illegal name of the instrument " + instrName);
		}
	}

	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		for (String s: instrumentlist.keySet()) {
			buffer.append(s + " " + instrumentlist.get(s) + ";");
		}
		return buffer.toString();
	}

}
